package com.jlu.controller;

import com.alibaba.fastjson.JSONObject;
import com.jlu.entity.Product;
import com.jlu.feignclient.ProductClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("CATEGORY")
public class CategoryController {

  private static final Logger log = LoggerFactory.getLogger(CategoryController.class);

  @Resource
  private ProductClient productClient;

  @GetMapping("category")
  public String invoke(){

    String product = productClient.product();
    String list = productClient.list();
    log.info("商品服务:{}",product);
    log.info("商品列表:{}",list);
    return "category is ok !!! " + product + list;
  }

//  queryString
  @GetMapping("test")
  public String query(HttpServletRequest request){
    System.out.println("请求头为： " + request.getHeader("user"));
    String test = productClient.test("林家慧", 22);
    return "test is ok !!!" + test ;
  }

//  路径传参
  @GetMapping("test1")
  public String path(){
    String test = productClient.test("慧宝", 22);
    return "test1 is ok !!!" + test;
  }

//  传递对象
  @PostMapping("test2")
  public String entity(){

    Product product = new Product();
    product.setId(1);
    product.setName("蓝光");
    product.setPrice(23.23);
    product.setBir(new Date());
    String test2 = productClient.test2(product);
    return "test2 is ok!!!" + test2;
  }

//  传递数组
  @GetMapping("test3")
  public String test3(){
    String[] ids = new String[]{"1","2","3"};
    String test3 = productClient.test3(ids);
    return "test3 is ok!!!" + test3;
  }

//  传递集合
  @GetMapping("test4")
  public String test4(){
    String[] ids = new String[]{"1","2","3"};
    String test4 = productClient.test4(ids);
    return "test4 is ok" + test4;
  }

//  id查询
  @GetMapping("test5")
  public String test5(){
    Product test5 = productClient.test5(23);
    return "test5 is ok!!!" + test5;
  }

//  以id查询list
  @GetMapping("test6")
  public List<Product> test6(){
    List<Product> list = productClient.list(1);
    return list;
  }

//  以id分页查询商品信息和总条数
  @GetMapping("test7")
  public String test7(){
    String map = productClient.findByCategoryIdAndPage(1, 2, 3);

//    json反序列化
    JSONObject jsonObject = JSONObject.parseObject(map);
    Object rows = jsonObject.get("rows");
    System.out.println(rows);

    List<Product> product = JSONObject.parseArray(rows.toString(), Product.class);

    for (Product product1 : product) {
      System.out.println(product1);
    }

    log.info("成功");
    return map;
  }
}
